/**
 * \ * JAVACC DEMO 1.0
 */
package com.apache.portal.thread;

import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.ConfigUtil;
import com.apache.uct.common.ToolsUtil;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:  将接口获取的数据转化为json文件
 *
 * @author Hou Dayu 创建时间：2016-12-29
 */
public class JsonDataInitSchedulerJob implements ISchedulerJob {

    private Logger log = Logger.getLogger(JsonDataInitSchedulerJob.class);

    private static transient boolean JsonDataInitTaskMark = true;//线程执行标志

    public JsonDataInitSchedulerJob() {
    }

    public void run() {
        try {
            if (JsonDataInitTaskMark) {
                JsonDataInitTaskMark = false;
                List list = initCache();
                if (null == list || list.size() <= 0)
                    return;
                int count = list.size();
                for (int i = 0; i < count; i++) {
                    Map<String, String> data = (Map) list.get(i);
                    initJson(data);
                }
                JsonDataInitTaskMark = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JsonDataInitTaskMark = true;
        }
    }

    private List initCache() {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("modelTypes", "s_sysDataUrl");
        param.put("resultType", "objInfo");
        param.put("sqlKeyId", "objInfo");
        param.put("datasource", "cms");
        param.put("sysPass", ConfigUtil.getInstance().interfacePass());
        ResultEntity entity = LoadRpcService.service()
                .doServiceClient(PortalPubFactory.getInstance().getBeanId("cms"), "dymicSql", param,
                        PortalPubFactory.getInstance().getRpcInfo("wcm"));
        if (!ToolsUtil.isEmpty(entity.getEntity())) {
            List list = (List) entity.getEntity();
            return list;
        } else {
            log.error("没有获取到DataUrl信息");
        }
        return null;
    }

    private void initJson(Map<String, String> data) {

        try {
            String path = ToolsUtil.getInstance()
                    .getValueByKey("config.properties", "html_path");
            path = path.replaceAll("/wcm", "");
            String folderPath = Validator
                    .getDefaultStr(String.valueOf(data.get("dataAddress")), path);
            String channelCode = String.valueOf(data.get("channelCode"));
            String dataUrl = String.valueOf(data.get("dataUrl"));
            if (Validator.isNotNull(channelCode) && Validator.isNotNull(dataUrl)) {
                URL url = new URL(dataUrl);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();
                InputStream inputStream = urlConnection.getInputStream();
                String responseStr = IOUtils.toString(inputStream, "UTF-8");
                System.out.println(responseStr);
                String fileName = path + folderPath + "/" + channelCode + ".json";
                FileOperateUtil.newCreateFolder(path + folderPath);
                boolean returnFalg = FileOperateUtil.newCreateFile(fileName, responseStr, "UTF-8");
                log.info("数据文件生成：" + fileName + "   |   " + returnFalg);
            }

        } catch (Exception e) {
            throw new BusinessException("数据静态化失败：" + e.getMessage());
        }
        //        Map param = new HashMap();
        //        param.put("resultType", "processSql");
        //        param.put("sysPass", ConfigUtil.getInstance().interfacePass());
        //        param.put("sqlKeyId", "T005");
        //        param.put("beforMethodKey", "T005");
        //        param.put("modelTypes", "u_sysDataUrl");
        //        param.put("sysDataUrl.w_infoId", data.get("infoId"));
        //        param.put("sysDataUrl.conversion", "T");
        //        param.put("dataUrl", data.get("dataUrl"));
        //        param.put("fileName", data.get("channelCode"));
        //        param.put("folderPath", data.get("dataAddress"));
        //        ResultEntity entity = LoadRpcService.service()
        //                .doServiceClient("iusService", "dymicSql", param,
        //                        PortalPubFactory.getInstance().getRpcInfo("ius"));
        //        log.error("静态化结果(" + data.get("dataUrl") + ")：" + entity.getMessage());
    }

}
